<template>
    <div class="user-container">
        <!-- 左侧用户信息 -->
        <div class="user-info">
            <el-card class="user-card" v-loading="userLoading">
                <div class="user-header">
                    <el-avatar :size="100" :src="userInfo?.avatar || defaultAvatar"></el-avatar>
                    <h2>{{ userInfo?.nickname || '未设置昵称' }}</h2>
                    <p class="user-email">{{ userInfo?.username }}</p>
                </div>
                <el-divider></el-divider>
                <div class="user-details">
                    <div class="detail-item">
                        <span class="label">用户名：</span>
                        <span class="value">{{ userInfo?.username }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">自我介绍：</span>
                        <span class="value">{{ userInfo?.introduce }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">注册时间：</span>
                        <span class="value">{{ formatDate(userInfo?.createTime) }}</span>
                    </div>
                </div>
                <div>
                    <el-button type="primary" @click="showEditDialog" class="edit-btn">编辑资料</el-button>
                </div>
                <div>
                    <el-button type="success" @click="showResumeDialog" class="edit-btn">编辑简历</el-button>
                </div>
            </el-card>
        </div>

        <!-- 右侧投递记录 -->
        <div class="delivery-records">
            <el-card v-loading="loading">
                <div slot="header">
                    <span style="font-weight: 600;">投递记录</span>
                </div>
                <el-table :data="deliveryRecords" style="width: 100%" :loading="loading">
                    <el-table-column prop="name" label="职位名称"></el-table-column>
                    <el-table-column prop="nickname" label="用户"></el-table-column>
                    <el-table-column prop="createTime" label="投递时间"></el-table-column>
                    <el-table-column label="状态">
                        <template slot-scope="scope">
                            <el-tag>{{ getStatusType(scope.row.deliverStatus) }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" @click="viewJobDetail(scope.row)">查看详情</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-container">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page="filterForm.currPage" :page-sizes="[10, 20, 30, 50]"
                        :page-size="filterForm.pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </el-card>
        </div>

        <!-- 编辑资料弹窗 -->
        <el-dialog title="编辑个人资料" :visible.sync="editDialogVisible" width="500px">
            <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="介绍" prop="introduce">
                    <el-input v-model="editForm.introduce"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <MyUpload ref="childUpload" @callParent="transDownloadUrl"></MyUpload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEdit" :loading=loading>确 定</el-button>
            </div>
        </el-dialog>

        <!-- 编辑简历弹窗 -->
        <el-dialog title="编辑简历" :visible.sync="resumeDialogVisible" width="500px">
            <el-form :model="resumeForm" :rules="resumeRules" ref="resumeForm" label-width="100px">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="resumeForm.name"></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="resumeForm.age" :min="18" :max="100"></el-input-number>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="resumeForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="resumeForm.email"></el-input>
                </el-form-item>
                <el-form-item label="学校" prop="school">
                    <el-input v-model="resumeForm.school"></el-input>
                </el-form-item>
                <el-form-item label="学历" prop="education">
                    <el-select v-model="resumeForm.education" placeholder="请选择学历">
                        <el-option label="大专" value="大专"></el-option>
                        <el-option label="本科" value="本科"></el-option>
                        <el-option label="硕士" value="硕士"></el-option>
                        <el-option label="博士" value="博士"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="resumeForm.sex">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="专业" prop="major">
                    <el-input v-model="resumeForm.major"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resumeDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitResume" :loading="loading">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 职位详情弹窗 -->
        <el-dialog title="岗位详情" :visible.sync="detailDialogVisible" width="60%">
            <div class="job-detail" v-if="currentJob">
                <div class="detail-header">
                    <div class="detail-title">
                        <h2>{{ currentJob.name }}</h2>
                    </div>
                </div>
                <el-divider></el-divider>
                <div class="detail-content">
                    <div class="detail-section">
                        <h3>职位要求</h3>
                        <div class="requirement-list">
                            <div class="requirement-item">
                                <span class="label">工作地点：</span>
                                <span class="value">{{ currentJob.address }}</span>
                            </div>
                            <div class="requirement-item">
                                <span class="label">工作经验：</span>
                                <span class="value">{{ currentJob.experience }}</span>
                            </div>
                            <div class="requirement-item">
                                <span class="label">学历要求：</span>
                                <span class="value">{{ currentJob.education }}</span>
                            </div>
                            <div class="requirement-item">
                                <span class="label">岗位薪资：</span>
                                <span class="value">{{ currentJob.salary }}元</span>
                            </div>
                        </div>
                    </div>
                    <div class="detail-section">
                        <h3>职位描述/任职资格</h3>
                        <div class="job-description" v-html="currentJob.introduce"></div>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getDeliverList, getUserInfo, getUserSubmit, getJobDetail, getResumeSubmit, getResumeInfo } from '@/api';
import MyUpload from '@/components/upload';

export default {
    components: {
        MyUpload
    },
    name: 'User',
    data() {
        return {
            userInfo: {},
            defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            deliveryRecords: [],
            editDialogVisible: false,
            loading: false,
            deliverLoading: false,
            userLoading: false,
            total: 0,
            editForm: {
                nickname: '',
                introduce: '',
                avatar: ''
            },
            filterForm: {
                currPage: 1,
                pageSize: 10,
            },
            editRules: {
                nickname: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                introduce: [
                    { required: true, message: '请输入个人简介', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ]
            },
            jobDetailVisible: false,
            jobDetailLoading: false,
            detailDialogVisible: false,
            currentJob: {},
            resumeDialogVisible: false,
            resumeForm: {
                name: '',
                age: 18,
                phone: '',
                email: '',
                school: '',
                education: '',
                sex: '',
                major: ''
            },
            resumeRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                age: [
                    { required: true, message: '请输入年龄', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                school: [
                    { required: true, message: '请输入学校', trigger: 'blur' }
                ],
                education: [
                    { required: true, message: '请选择学历', trigger: 'change' }
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                major: [
                    { required: true, message: '请输入专业', trigger: 'blur' }
                ]
            }
        }
    },
    mounted() {
        this.getUser();
        this.getDeliveryRecords();
    },
    methods: {
        transDownloadUrl(url) {
            this.editForm.avatar = url;
        },
        getUser() {
            this.userLoading = true;
            getUserInfo().then(res => {
                this.userInfo = res.data;
                this.userLoading = false;
            }).catch(err => {
                this.userLoading = false;
                this.$message.error(err.msg);
            })
        },
        getDeliveryRecords() {
            this.loading = true;
            getDeliverList(this.filterForm).then(res => {
                this.deliveryRecords = res.data.list;
                this.total = parseInt(res.data.total);
                this.loading = false;
            }).catch(err => {
                this.$message.error(err.msg);
            })
        },
        handleEdit() {
            this.editDialogVisible = true;
            this.editForm = Object.assign({}, this.userInfo);
        },
        handleEditClose() {
            this.editDialogVisible = false;
            this.$refs.editForm.resetFields();
        },
        handleEditSubmit() {
            this.$refs.editForm.validate(valid => {
            })
        },
        formatDate(date) {
            if (!date) return '暂无';
            return new Date(date).toLocaleString();
        },
        getStatusType(status) {
            const statusMap = {
                1: '投递中',
                2: '面试中',
                3: '通过',
                4: '没通过'
            };
            return statusMap[status] || 'info';
        },
        showEditDialog() {
            this.editForm = {
                username: this.userInfo.username,
                nickname: this.userInfo.nickname,
                introduce: this.userInfo.introduce,
                avatar: this.userInfo.avatar,
                id: this.userInfo.id
            }
            this.editDialogVisible = true;
        },
        submitEdit() {
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    getUserSubmit(this.editForm).then(res => {
                        localStorage.setItem('userInfo', JSON.stringify(res.data));
                        this.$message.success('更新成功');
                        this.loading = false;
                    }).catch(err => {
                        this.$message.error(err.msg);
                        this.loading = false;
                    })
                }
            });
        },
        handleAvatarSuccess(res) {
            this.editForm.avatar = res.url;
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        viewJobDetail(record) {
            this.detailDialogVisible = true;
            this.currentJob = {
                name: record.name,
                companyName: record.company,
                companyAvatar: record.companyAvatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                companyDesc: record.companyDesc || '暂无公司简介',
                address: record.location || '暂无工作地点',
                experience: record.experience || '暂无经验要求',
                education: record.education || '暂无学历要求',
                salary: record.salary || '暂无薪资信息',
                introduce: record.description || '暂无职位描述'
            };
        },
        handleSizeChange(val) {
            this.filterForm.pageSize = val;
            this.getDeliveryRecords();
        },
        handleCurrentChange(val) {
            this.filterForm.currPage = val;
            this.getDeliveryRecords();
        },
        showResumeDialog() {
            this.resumeDialogVisible = true;
            this.loading = true;
            getResumeInfo().then(res => {
                if (res.data) {
                    this.resumeForm = {
                        name: res.data.name || '',
                        age: res.data.age || 18,
                        phone: res.data.phone || '',
                        email: res.data.email || '',
                        school: res.data.school || '',
                        education: res.data.education || '',
                        sex: res.data.sex || '男',
                        major: res.data.major || ''
                    };
                } else {
                    // 如果没有简历信息，使用默认值
                    this.resumeForm = {
                        name: '',
                        age: 18,
                        phone: '',
                        email: '',
                        school: '',
                        education: '',
                        sex: '男',
                        major: ''
                    };
                }
                this.loading = false;
            }).catch(err => {
                this.$message.error(err.msg || '获取简历信息失败');
                this.loading = false;
            });
        },
        submitResume() {
            this.$refs.resumeForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    getResumeSubmit(this.resumeForm).then(res => {
                        this.$message.success('简历保存成功');
                        this.resumeDialogVisible = false;
                        this.loading = false;
                    }).catch(err => {
                        this.$message.error(err.msg || '简历保存失败');
                        this.loading = false;
                    });
                }
            });
        }
    }
}
</script>

<style scoped>
.user-container {
    padding: 20px;
    display: flex;
    gap: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.user-info {
    width: 300px;
    flex-shrink: 0;
}

.delivery-records {
    flex-grow: 1;
}

.user-card {
    text-align: center;
}

.user-header {
    padding: 20px 0;
}

.user-header h2 {
    margin: 10px 0;
    font-size: 20px;
}

.user-email {
    color: #666;
    font-size: 14px;
}

.user-details {
    text-align: left;
    padding: 0 20px;
}

.detail-item {
    margin: 10px 0;
    font-size: 14px;
}

.detail-item .label {
    color: #666;
    margin-right: 10px;
}

.edit-btn {
    margin-top: 20px;
    width: 100%;
}

.avatar-uploader {
    text-align: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.job-detail-header {
    text-align: center;
    margin-bottom: 20px;
}

.job-detail-header h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    color: #303133;
}

.job-meta {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.job-meta .company {
    font-size: 16px;
    color: #606266;
}

.job-detail-content {
    padding: 0 20px;
}

.detail-header {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.detail-title {
    margin-bottom: 20px;
}

.detail-title h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
}

.detail-company {
    display: flex;
    align-items: center;
    gap: 15px;
}

.company-logo {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    object-fit: cover;
}

.company-info {
    flex: 1;
}

.company-name {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 5px;
}

.company-desc {
    font-size: 14px;
    color: #606266;
}

.detail-content {
    padding: 20px;
}

.detail-section {
    margin-bottom: 20px;
}

.detail-section h3 {
    font-size: 16px;
    color: #303133;
    margin-bottom: 10px;
}

.requirement-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    margin-top: 10px;
}

.requirement-item {
    display: flex;
    align-items: center;
}

.requirement-item .label {
    color: #606266;
    margin-right: 10px;
    min-width: 80px;
}

.requirement-item .value {
    color: #303133;
}

.job-description {
    margin-top: 10px;
    line-height: 1.6;
    color: #606266;
}
</style>